import React, { useState, useEffect, useRef } from "react";
import { Card, Col, Row, List, Avatar, Drawer } from "antd";
import {
  EditOutlined,
  EllipsisOutlined,
  SettingOutlined,
} from "@ant-design/icons";
import axios from "axios";
import * as echarts from "echarts";
import _ from "lodash";

export default function Home() {
  const [viewList, setViewList] = useState([]);
  const [likeList, setLikeList] = useState([]);
  const [pieVisible, setPieVisible] = useState(false);
  const [pieChart, setPieChart] = useState(null);
  const [pieChartData, setPieChartData] = useState(null);
  const barRef = useRef();
  const pieRef = useRef();
  const { Meta } = Card;
  const {
    username,
    region,
    role: { roleName },
  } = JSON.parse(localStorage.getItem("token"));
  useEffect(() => {
    axios
      .get(
        "http://localhost:5000/news?publishState=2&_expand=category&_sort=view&_order=desc&_limit=10"
      )
      .then((res) => {
        setViewList(res.data);
      });
  }, []);
  useEffect(() => {
    axios
      .get(
        "http://localhost:5000/news?publishState=2&_expand=category&_sort=star&_order=desc&_limit=10"
      )
      .then((res) => {
        setLikeList(res.data);
      });
  }, []);
  useEffect(() => {
    axios
      .get("http://localhost:5000/news?publishState=2&_expand=category")
      .then((res) => {
        // 利用lodash对数据进行处理
        // console.log(_.groupBy(res.data, (item) => item.category.title));
        renderBarView(_.groupBy(res.data, (item) => item.category.title));
        var listSelf = res.data.filter((item) => item.author === username);
        // console.log(listSelf);
        setPieChartData(_.groupBy(listSelf, (item) => item.category?.title));
      });
    // 组件销毁时关闭窗口自适应
    return () => {
      window.onresize = null;
    };
  }, [username]);
  // 渲染柱状图
  const renderBarView = (barDataObj) => {
    // 基于准备好的dom，初始化echarts实例
    var myChart = echarts.init(barRef.current);
    // 绘制图表
    myChart.setOption({
      title: {
        text: "新闻分类图示",
      },
      tooltip: {},
      xAxis: {
        data: Object.keys(barDataObj),
        axisLabel: {
          rotate: "45",
          fontSize: 20,
        },
      },
      yAxis: {
        minInterval: 1,
      },
      series: [
        {
          name: "",
          type: "bar",
          data: Object.values(barDataObj).map((item) => item.length),
        },
      ],
    });
    // 监听窗口大小变化
    window.onresize = () => {
      myChart.resize();
    };
  };
  // 渲染扇形图
  const renderPieView = (pieChartData) => {
    // 避免扇形图的多次初始化渲染
    var myChart;
    if (!pieChart) {
      // 基于准备好的dom，初始化echarts实例
      myChart = echarts.init(pieRef.current);
      setPieChart(true);
    } else {
      return;
    }
    // 绘制图表
    myChart.setOption({
      title: {
        text: "个人新闻分类",
        subtext: username,
        left: "center",
      },
      tooltip: {
        trigger: "item",
      },
      legend: {
        orient: "vertical",
        left: "left",
      },
      series: [
        {
          name: "Access From",
          type: "pie",
          radius: "50%",
          data: Object.keys(pieChartData).map((item) => {
            return { value: pieChartData[item].length, name: item };
          }),
          // data: [
          //   { value: 1048, name: "Search Engine" },
          //   { value: 735, name: "Direct" },
          //   { value: 580, name: "Email" },
          //   { value: 484, name: "Union Ads" },
          //   { value: 300, name: "Video Ads" },
          // ]
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)",
            },
          },
        },
      ],
    });
    // 监听窗口大小变化
    window.onresize = () => {
      myChart.resize();
    };
  };

  const pieShow = () => {
    setTimeout(() => {
      renderPieView(pieChartData);
    }, 0);
    setPieVisible(true);
  };
  const onClose = () => {
    setPieVisible(false);
  };
  return (
    <div className="site-card-wrapper">
      <Row gutter={16}>
        <Col span={8}>
          <Card title="访问最多" bordered={true}>
            <List
              size="large"
              dataSource={viewList}
              renderItem={(item) => (
                <List.Item>
                  <a
                    href={`http://localhost:3000/#/news-manage/preview/${item.id}/`}
                  >
                    {item.title}
                  </a>
                </List.Item>
              )}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card title="点赞最多" bordered={true}>
            <List
              size="large"
              dataSource={likeList}
              renderItem={(item) => (
                <List.Item>
                  <a
                    href={`http://localhost:3000/#/news-manage/preview/${item.id}/`}
                  >
                    {item.title}
                  </a>
                </List.Item>
              )}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card
            style={{ width: 300 }}
            cover={
              <img
                alt="example"
                src="https://gw.alipayobjects.com/zos/rmsportal/JiqGstEfoWAOHiTxclqi.png"
              />
            }
            actions={[
              <SettingOutlined key="setting" onClick={() => pieShow()} />,
              <EditOutlined key="edit" />,
              <EllipsisOutlined key="ellipsis" />,
            ]}
          >
            <Meta
              avatar={<Avatar src="https://joeschmoe.io/api/v1/random" />}
              title={username}
              description={
                <div>
                  <b>{region ? region : "全球"}</b>
                  <b style={{ paddingLeft: "30px" }}>{roleName}</b>
                </div>
              }
            />
          </Card>
        </Col>
      </Row>
      <Drawer
        title="个人新闻分类"
        width="600px"
        placement="right"
        onClose={() => onClose()}
        visible={pieVisible}
      >
        <div
          ref={pieRef}
          id="main"
          style={{ marginTop: "30px", width: "100%", height: "400px" }}
        ></div>
      </Drawer>
      <div
        ref={barRef}
        id="main"
        style={{ marginTop: "30px", width: "100%", height: "400px" }}
      ></div>
    </div>
  );
}
